<template>
  <div>
    <px-form ref="checkRuleContentFormRef" :model="templateContentDTOList">
      <div v-for="(item, index) in templateContentDTOList" :key="index">
        <!-- 抄表项目 -->
        <EditDropDown v-if="item.inspectItemType === 1" :dropdownTitle="item.isTableEdit === 'edit' ? '抄表项目' : item.inspectItemContent">
          <template v-slot:btn>
            <px-button v-if="item.isTableEdit === 'view'" link type="primary" @click="editMeterJudgeTable(index)">编辑</px-button>
            <px-button v-if="item.isTableEdit === 'view'" link type="danger" @click="deleteMeterJudgeTable(index, item.id)">删除</px-button>
            <px-button v-if="item.isTableEdit === 'edit'" link type="primary" @click="saveMeterJudgeTable(checkRuleContentFormRef, index, '2')"
              >保存</px-button
            >
            <px-button v-if="item.isTableEdit === 'edit'" link type="primary" @click="cancelMeterJudgeTable(index)">取消</px-button>
          </template>
          <template v-slot:content>
            <px-form-item
              v-if="item.isTableEdit === 'edit'"
              label="巡检项内容"
              :prop="index + '.inspectItemContent'"
              :rules="[{ required: true, message: '巡检项内容不能为空', trigger: 'blur' }]"
            >
              <px-input v-model="item.inspectItemContent" placeholder="请输入巡检项内容" maxlength="50" clearable />
            </px-form-item>
            <px-table
              :data="item.contentItemDTOList"
              class="equip-table"
              :class="item.isTableEdit === 'view' ? 'inspect-table-view' : 'inspect-table-edit'"
              size="small"
              border
            >
              <px-table-column fixed="left" type="index" align="center" label="序号" width="60" />
              <px-table-column fixed="left" prop="meterReadingMode" label="抄表方式" width="207" show-overflow-tooltip>
                <template #header>
                  <div>
                    <label class="must">抄表方式</label>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.meterReadingModeDesc }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.meterReadingMode'"
                      :rules="[{ required: true, message: '抄表方式不能为空', trigger: 'blur' }]"
                    >
                      <px-radio-group v-model="scope.row.meterReadingMode" @change="val => handleRadioChange(scope.row, val)" size="large">
                        <px-radio-button :label="1">自动</px-radio-button>
                        <px-radio-button :label="2">手动</px-radio-button>
                      </px-radio-group>
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column fixed="left" prop="meterReadingItem" label="抄表项" min-width="160" show-overflow-tooltip>
                <template #header>
                  <div>
                    <label class="must">抄表项</label>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.meterReadingItem }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.meterReadingItem'"
                      :rules="[{ required: true, message: '抄表项不能为空', trigger: 'blur' }]"
                    >
                      <px-input v-model="scope.row.meterReadingItem" placeholder="请输入抄表项" maxlength="50" clearable />
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column prop="unit" label="单位" min-width="100" show-overflow-tooltip>
                <template #header>
                  <div>
                    <label class="must">单位</label>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.unit }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.unit'"
                      :rules="[{ required: true, message: '单位不能为空', trigger: 'blur' }]"
                    >
                      <px-input v-model="scope.row.unit" placeholder="请输入单位" maxlength="50" clearable />
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column prop="maxValue" label="最大值" min-width="100" show-overflow-tooltip>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.maxValue }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList' + scope.$index + '.maxValue'"
                      :rules="[{ validator: (rule, value, callback) => validateMaxValueAndMinValue(value, scope, callback), trigger: 'blur' }]"
                    >
                      <px-input v-model="scope.row.maxValue" placeholder="请输入最大值" maxlength="50" clearable />
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column prop="minValue" label="最小值" min-width="100" show-overflow-tooltip>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.minValue }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.minValue'"
                      :rules="[{ validator: (rule, value, callback) => validateMaxValueAndMinValue(value, scope, callback), trigger: 'blur' }]"
                    >
                      <px-input v-model="scope.row.minValue" placeholder="请输入最小值" maxlength="50" clearable />
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column v-if="item.isTableEdit === 'edit'" fixed="right" label="操作" width="60" align="center">
                <template #default="scope">
                  <px-button
                    link
                    type="danger"
                    icon="Delete"
                    :disabled="scope.$index === 0 && templateContentDTOList[index].contentItemDTOList.length === 1"
                    @click="deleteMeterJudgeItem(index, scope.row, scope.$index)"
                  />
                </template>
              </px-table-column>
            </px-table>
            <div
              v-if="item.isTableEdit === 'edit'"
              style="
                width: 100%;
                height: 32px;
                margin-bottom: 18px;
                line-height: 32px;
                color: #3b82f6;
                text-align: center;
                cursor: pointer;
                border: 1px dashed #3b82f6;
                border-radius: 4px;
              "
              @click="addMeterJudgeTableItem(index, '2')"
            >
              新增抄表项
            </div>
          </template>
        </EditDropDown>
        <!-- 判断项目 -->
        <EditDropDown v-if="item.inspectItemType === 2" :dropdownTitle="item.isTableEdit === 'edit' ? '判断项目' : item.inspectItemContent">
          <template v-slot:btn>
            <px-button v-if="item.isTableEdit === 'view'" link type="primary" @click="editMeterJudgeTable(index)">编辑</px-button>
            <px-button v-if="item.isTableEdit === 'view'" link type="danger" @click="deleteMeterJudgeTable(index, item.id)">删除</px-button>
            <px-button v-if="item.isTableEdit === 'edit'" link type="primary" @click="saveMeterJudgeTable(checkRuleContentFormRef, index, '1')"
              >保存</px-button
            >
            <px-button v-if="item.isTableEdit === 'edit'" link type="primary" @click="cancelMeterJudgeTable(index)">取消</px-button>
          </template>
          <template v-slot:content>
            <px-form-item
              v-if="item.isTableEdit === 'edit'"
              label="巡检项内容"
              :prop="index + '.inspectItemContent'"
              :rules="[{ required: true, message: '巡检项内容不能为空', trigger: 'blur' }]"
            >
              <px-input v-model="item.inspectItemContent" placeholder="请输入巡检项内容" maxlength="50" clearable />
            </px-form-item>
            <px-table
              :data="item.contentItemDTOList"
              class="equip-table"
              :class="item.isTableEdit === 'view' ? 'inspect-table-view' : 'inspect-table-edit'"
              size="small"
              border
            >
              <px-table-column v-if="item.isTableEdit === 'view'" fixed="left" type="index" label="序号" width="60" />
              <px-table-column
                v-if="baseInfoFormValue?.inspectContentType === 1"
                fixed="left"
                prop="eqpStatus"
                label="适用设备状态"
                min-width="160"
                show-overflow-tooltip
              >
                <template #header>
                  <div>
                    <label class="must">适用设备状态</label>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.eqpStatusListDesc }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.eqpStatusList'"
                      :rules="[{ required: true, message: '适用设备状态不能为空', trigger: 'blur' }]"
                    >
                      <px-select
                        v-model="scope.row.eqpStatusList"
                        placeholder="请选择适用设备状态"
                        collapse-tags-tooltip
                        collapse-tags
                        multiple
                        filterable
                        clearable
                        @change="value => handleStatusChange(value, scope.row)"
                      >
                        <px-option v-for="item in eqpRunStatusList" :key="item.id" :label="item.name" :value="item.value" />
                      </px-select>
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column fixed="left" prop="inspectItem" label="巡检项" min-width="160" show-overflow-tooltip>
                <template #header>
                  <div>
                    <label class="must">巡检项</label>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.inspectItem }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.inspectItem'"
                      :rules="[{ required: true, message: '巡检项不能为空', trigger: 'blur' }]"
                    >
                      <px-input v-model="scope.row.inspectItem" placeholder="请输入巡检项" maxlength="50" clearable />
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column prop="inspectContent" label="巡检内容" min-width="100" show-overflow-tooltip>
                <template #header>
                  <div>
                    <label class="must">巡检内容</label>
                  </div>
                </template>
                <template #default="scope">
                  <template v-if="item.isTableEdit === 'view'">{{ scope.row.inspectContent }}</template>
                  <template v-else>
                    <px-form-item
                      label-width="0px"
                      label=""
                      :prop="index + '.contentItemDTOList.' + scope.$index + '.inspectContent'"
                      :rules="[{ required: true, message: '巡检内容不能为空', trigger: 'blur' }]"
                    >
                      <px-input v-model="scope.row.inspectContent" placeholder="请输入巡检内容" maxlength="50" clearable />
                    </px-form-item>
                  </template>
                </template>
              </px-table-column>
              <px-table-column prop="inspectContentRangeValue" label="内容范围" min-width="160" show-overflow-tooltip>
                <template #default="scope">
                  <template v-if="scope.row.inspectContentRangeCode !== 4">
                    <template v-if="item.isTableEdit === 'view' && scope.row.inspectContentRangeCode === 1">文本</template>
                    <template v-if="item.isTableEdit === 'view' && scope.row.inspectContentRangeCode === 2">数字</template>
                    <template v-if="item.isTableEdit === 'view' && scope.row.inspectContentRangeCode === 3 && scope.row.inspectContentRangeValue">
                      判断：True={{ scope.row.inspectContentRangeValue.split(",")[0] }}; False={{ scope.row.inspectContentRangeValue.split(",")[1] }}
                    </template>
                    <template v-if="item.isTableEdit === 'edit' && scope.row.inspectContentRangeCode === 1">
                      <px-select v-model="scope.row.inspectContentRangeCode" placeholder="请选择内容范围" filterable style="width: 100%">
                        <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                      </px-select>
                    </template>
                    <template v-if="item.isTableEdit === 'edit' && scope.row.inspectContentRangeCode === 2">
                      <px-select v-model="scope.row.inspectContentRangeCode" placeholder="请选择内容范围" filterable style="width: 100%">
                        <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                      </px-select>
                    </template>
                    <template v-if="item.isTableEdit === 'edit' && scope.row.inspectContentRangeCode === 3">
                      <div class="flex-row">
                        <px-select v-model="scope.row.inspectContentRangeCode" placeholder="请选择内容范围" filterable style="width: 60%">
                          <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                        </px-select>
                        <px-form-item
                          label-width="0px"
                          label=""
                          :prop="index + '.contentItemDTOList.' + scope.$index + '.checkContentRangeValue1'"
                          :rules="[{ required: true, message: 'true不能为空', trigger: 'blur' }]"
                        >
                          &nbsp;&nbsp;True=
                          <px-input
                            v-model="scope.row.checkContentRangeValue1"
                            placeholder="请输入内容"
                            maxlength="50"
                            clearable
                            style="flex-grow: 1; width: 60%"
                          />
                        </px-form-item>
                        <px-form-item
                          label-width="0px"
                          label=""
                          :prop="index + '.contentItemDTOList.' + scope.$index + '.checkContentRangeValue2'"
                          :rules="[{ required: true, message: 'false不能为空', trigger: 'blur' }]"
                        >
                          &nbsp;&nbsp;False=
                          <px-input
                            v-model="scope.row.checkContentRangeValue2"
                            placeholder="请输入内容"
                            maxlength="50"
                            clearable
                            style="flex-grow: 1; width: 60%"
                          />
                        </px-form-item>
                        &nbsp;&nbsp;
                        <px-tooltip content="无法输入带逗号（','）的字符" placement="top">
                          <px-icon><QuestionFilled /></px-icon>
                        </px-tooltip>
                      </div>
                    </template>
                  </template>
                  <template v-else>
                    <template v-if="item.isTableEdit === 'view'"> 选择：{{ scope.row.inspectContentRangeValue }} </template>
                    <template v-else>
                      <px-form-item
                        label-width="0px"
                        label=""
                        :prop="index + '.contentItemDTOList.' + scope.$index + '.inspectContentRangeValue'"
                        :rules="[
                          {
                            required: item.isTableEdit === 'edit' && scope.row.inspectContentRangeCode === 4,
                            validator: checkRangeCode,
                            trigger: 'blur'
                          }
                        ]"
                      >
                        <px-input
                          v-model="scope.row.inspectContentRangeValue"
                          placeholder="请输入选项，并以英文逗号（','）分割"
                          maxlength="50"
                          clearable
                          style="width: 90%"
                        >
                          <template #prepend>
                            <px-select v-model="scope.row.inspectContentRangeCode" placeholder="请选择内容范围" filterable style="width: 120px">
                              <px-option v-for="item in checkContentRangeList" :key="item.value" :label="item.label" :value="item.value" />
                            </px-select>
                          </template>
                        </px-input>
                        &nbsp;&nbsp;
                        <px-tooltip content="以英文逗号（','）分割" placement="top">
                          <px-icon><QuestionFilled /></px-icon>
                        </px-tooltip>
                      </px-form-item>
                    </template>
                  </template>
                </template>
              </px-table-column>
              <px-table-column v-if="item.isTableEdit === 'edit'" fixed="right" label="操作" width="60" align="center">
                <template #default="scope">
                  <px-button
                    link
                    type="danger"
                    icon="Delete"
                    :disabled="scope.$index === 0 && templateContentDTOList[index].contentItemDTOList.length === 1"
                    @click="deleteMeterJudgeItem(index, scope.row, scope.$index)"
                  />
                </template>
              </px-table-column>
            </px-table>
            <div
              v-if="item.isTableEdit === 'edit'"
              style="
                width: 100%;
                height: 32px;
                margin-bottom: 18px;
                line-height: 32px;
                color: #3b82f6;
                text-align: center;
                cursor: pointer;
                border: 1px dashed #3b82f6;
                border-radius: 4px;
              "
              @click="addMeterJudgeTableItem(index, '1')"
            >
              新增巡检项
            </div>
          </template>
        </EditDropDown>
      </div>
    </px-form>
    <!-- 操作按钮 -->
    <div>
      <div v-if="showCheckRuleContent" style="margin-top: 16px">
        <px-button type="primary" @click="addMeterJudgeTable('1')">新增抄表项目</px-button>
        <px-button type="primary" @click="addMeterJudgeTable('2')">新增判断项目</px-button>
        <px-popover popper-class="popover-out" placement="bottom" popper-style="padding: 0" :width="160" trigger="hover">
          <template #reference>
            <px-button type="primary" plain>下载导入模板</px-button>
          </template>
          <ul class="popover-list">
            <li class="popover-list-item" @click="download('/digitaltwins/api/v1/inspectTemplate/meterTemplateDownLoad', '抄表项目模板')">
              <px-button link>抄表项目模板</px-button>
            </li>
            <li class="popover-list-item" @click="download('/digitaltwins/api/v1/inspectTemplate/decideTemplateDownLoad', '判断项目模板')">
              <px-button link>判断项目模板</px-button>
            </li>
          </ul>
        </px-popover>
        <px-popover popper-class="popover-out" placement="bottom" popper-style="padding: 0" :width="160" trigger="hover">
          <template #reference>
            <px-button type="primary" plain>导入巡检内容</px-button>
          </template>
          <ul class="popover-list">
            <li class="popover-list-item">
              <BatchUpload
                url="/ifp/digitaltwins/api/v1/inspectTemplate/meterImportData"
                permission="ALL_EQUIP_SPAREPARTS_LEDGER_BATCH_UPLOAD"
                :needResponse="true"
                @updateUploadPage="queryTable"
              >
                <px-button link>导入抄表项内容</px-button>
              </BatchUpload>
            </li>
            <li class="popover-list-item">
              <BatchUpload
                url="/ifp/digitaltwins/api/v1/inspectTemplate/decideImportData"
                permission="ALL_EQUIP_SPAREPARTS_LEDGER_BATCH_UPLOAD"
                :needResponse="true"
                @updateUploadPage="queryTable"
              >
                <px-button link>导入判断项内容</px-button>
              </BatchUpload>
            </li>
          </ul>
        </px-popover>
      </div>
    </div>
    <!-- 选择设备弹窗 -->
    <EquipIdSelectDialog
      :visible="dialogVisible"
      :className="baseInfoFormValue.className"
      :systemCodes="baseInfoFormValue.systemCodes"
      :categoryId="baseInfoFormValue.categoryId"
      :typeId="baseInfoFormValue.typeId"
      :modelId="baseInfoFormValue.modelId"
      @closeEquipDialog="closeEquipDialog"
      @changeEqpId="changeEqpId"
    />
  </div>
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import { cloneDeep } from "@pureadmin/utils";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, getCurrentInstance, onMounted, reactive, toRefs, watch, watchEffect } from "vue";
const ruleContent = defineModel("ruleContent");
const baseInfoFormValue = computed(() => props.baseInfoFormValue);
const { proxy } = getCurrentInstance();
// 页面本身的值
const state = reactive<any>({
  // 第2步：巡检内容
  checkRuleContentFormRef: null,
  checkContentRangeList: [
    { label: "文本", value: 1 },
    { label: "数字", value: 2 },
    { label: "判断", value: 3 },
    { label: "选择", value: 4 }
  ], // 巡检内容范围列表
  templateContentDTOList: [], // 巡检内容总表格，可以遍历
  dialogVisible: false,
  cellInfo: {},
  eqpRunStatusList: [], // 设备运行状态下拉框
  templateContentDTOListTemp: [] // 临时保存巡检内容表格数据，为了取消使用
});
const {
  checkRuleContentFormRef,
  checkContentRangeList,
  templateContentDTOList,
  dialogVisible,
  cellInfo,
  eqpRunStatusList,
  templateContentDTOListTemp
} = toRefs(state);
const props = defineProps(["baseInfoFormValue", "defaultData"]);
watch(
  () => props.defaultData,
  () => {
    if (props.defaultData) {
      templateContentDTOList.value = props.defaultData.map(item => {
        const { contentItemDTOList } = item;
        const arr = contentItemDTOList.map(contentItem => {
          const { eqpStatusList } = contentItem;
          return {
            ...contentItem,
            eqpStatusList: eqpStatusList?.map(statusItem => statusItem.value),
            eqpStatusListDesc: eqpStatusList?.map(statusItem => statusItem.name).join("/")
          };
        });
        return { ...item, contentItemDTOList: arr, isTableEdit: "view" };
      });
    }
  }
);
watchEffect(() => {
  ruleContent.value = cloneDeep(templateContentDTOList.value);
});
onMounted(() => {
  if (baseInfoFormValue.value?.inspectContentType === 1) {
    querySelectList();
  }
});
const queryTable = res => {
  if (res.success && res.data?.length) {
    const data = res.data.map(item => {
      const { contentItemDTOList } = item;
      const arr = contentItemDTOList.map(contentItem => {
        const { eqpStatusList } = contentItem;
        return {
          ...contentItem,
          eqpStatusList: eqpStatusList?.map(statusItem => statusItem.value),
          eqpStatusListDesc: eqpStatusList?.map(statusItem => statusItem.name).join("/")
        };
      });
      return { ...item, contentItemDTOList: arr, isTableEdit: "view" };
    });
    templateContentDTOList.value = [...templateContentDTOList.value, ...data];
  }
};
// 适用设备运行状态改变
const handleStatusChange = (data, row) => {
  const statusDescArr = [];
  eqpRunStatusList.value.forEach(item => {
    if (data.includes(item.value)) {
      statusDescArr.push(item.name);
    }
  });
  row.eqpStatusListDesc = statusDescArr.join("/");
};
// 搜索查询条件下拉框
const querySelectList = async () => {
  eqpRunStatusList.value = await queryDictData({ typeCode: "EQP_RUN_STATUS" });
};
const handleRadioChange = (row, val) => {
  if (val === 1) {
    row.meterReadingModeDesc = "自动";
  } else {
    row.meterReadingModeDesc = "手动";
  }
};
const download = async (downloadUrl, name) => {
  await proxy.download("GET", downloadUrl, {}, name);
  PxMessage.success("模板已下载");
};
// 关闭子级设备dialog弹窗
const closeEquipDialog = () => {
  dialogVisible.value = false;
};
// 判断项目-内容范围-选择
const checkRangeCode = (rule: any, value: any, callback: any) => {
  if (value == "") {
    callback(new Error("选项不能为空"));
  } else if (!/,/.test(value)) {
    callback(new Error("请输入选项，并以英文逗号（','）分割"));
  } else {
    callback();
  }
};
const validateMaxValueAndMinValue = (value: any, scope: any, callback: any) => {
  const { maxValue, minValue } = scope.row;
  const flag = Number(maxValue) < Number(minValue);
  const maxFlag = maxValue && maxValue !== 0;
  const minFlag = minValue && minValue !== 0;
  if (maxFlag && minFlag && flag) {
    callback(new Error("最大值不能小于最小值"));
  } else {
    callback();
  }
};
// 展示新增抄表项目、新增判断项目
const showCheckRuleContent = computed(() => {
  if (
    templateContentDTOList.value.length === 0 ||
    templateContentDTOList.value.every(item => {
      return item.isTableEdit === "view" || !item.isTableEdit;
    })
  ) {
    return true;
  }
  return false;
});
// 第2步：巡检内容
// 新增抄表项目表格
const addMeterJudgeTable = val => {
  if (val === "1") {
    templateContentDTOList.value.push({
      inspectItemContent: "",
      inspectItemType: 1,
      inspectItemTypeDesc: "抄表项",
      isTableEdit: "edit",
      contentItemDTOList: [
        {
          meterReadingMode: 1,
          meterReadingModeDesc: "自动",
          meterReadingItem: "",
          unit: "",
          maxValue: "",
          minValue: "",
          eqpId: "",
          autoMeterReadingPoint: ""
        }
      ]
    });
  } else if (val === "2") {
    templateContentDTOList.value.push({
      inspectItemContent: "",
      inspectItemType: 2,
      inspectItemTypeDesc: "判断项",
      isTableEdit: "edit",
      contentItemDTOList: [
        {
          inspectItem: "",
          inspectContent: "",
          inspectContentRangeCode: 1,
          inspectContentRangeValue: ""
        }
      ]
    });
  }
  templateContentDTOListTemp.value[templateContentDTOList.value.length - 1] = JSON.parse(
    JSON.stringify(templateContentDTOList.value[templateContentDTOList.value.length - 1])
  );
};
// 保存抄表项目表格
const saveMeterJudgeTable = async (formEl, index, val) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (val === "1") {
        // 判断项目
        if (templateContentDTOList.value[index].contentItemDTOList && templateContentDTOList.value[index].contentItemDTOList.length > 0) {
          templateContentDTOList.value[index].contentItemDTOList.forEach(item => {
            if (item.inspectContentRangeCode === 3) {
              item.inspectContentRangeValue = item.checkContentRangeValue1 + "," + item.checkContentRangeValue2;
            }
          });
        }
      }
      templateContentDTOList.value[index].isTableEdit = "view";
    }
  });
};
// 取消抄表项目、判断项目表格
const cancelMeterJudgeTable = index => {
  PxMessageBox.confirm("内容没保存，确认取消?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "info",
    draggable: true
  })
    .then(async () => {
      if (templateContentDTOListTemp.value[index].inspectItemContent) {
        // checkItemContent存在为编辑，取消编辑回退到未编辑状态
        templateContentDTOList.value[index] = templateContentDTOListTemp.value[index];
        templateContentDTOListTemp.value[index] = JSON.parse(JSON.stringify(templateContentDTOList.value[index]));
      } else {
        templateContentDTOList.value = templateContentDTOList.value.slice(0, index);
        templateContentDTOListTemp.value = templateContentDTOListTemp.value.slice(0, index);
      }
      templateContentDTOList.value[index].isTableEdit = "view";
    })
    .catch(() => {});
};
// 编辑抄表项目、判断项目表格
const editMeterJudgeTable = index => {
  templateContentDTOList.value[index].isTableEdit = "edit";
  templateContentDTOListTemp.value[index] = templateContentDTOList.value[index];
  if (templateContentDTOList.value[index].contentItemDTOList && templateContentDTOList.value[index].contentItemDTOList.length > 0) {
    templateContentDTOList.value[index].contentItemDTOList.forEach(item => {
      if (item.inspectContentRangeCode === 3) {
        item.checkContentRangeValue1 = item.inspectContentRangeValue.split(",")[0];
        item.checkContentRangeValue2 = item.inspectContentRangeValue.split(",")[1];
      }
    });
  }
  templateContentDTOListTemp.value[index] = JSON.parse(JSON.stringify(templateContentDTOList.value[index]));
  templateContentDTOListTemp.value[index].isTableEdit = "view";
};
// 删除抄表项目、判断项目表
const deleteMeterJudgeTable = (index, id) => {
  PxMessageBox.confirm("是否要删除当前内容?", "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      // 调用接口
      if (id) {
        // await deleteInspectRuleContent(id);
        PxMessage.success("删除成功");
        templateContentDTOList.value.splice(index, 1);
      } else {
        templateContentDTOList.value.splice(index, 1);
      }
    })
    .catch(() => {});
};
// 新增抄表项目、判断项目某一行
const addMeterJudgeTableItem = (index, val) => {
  if (val === "1") {
    // 抄表项目
    templateContentDTOList.value[index].contentItemDTOList.push({
      inspectItem: "",
      inspectContent: "",
      inspectContentRangeCode: 1,
      inspectContentRangeValue: ""
    });
  } else if (val === "2") {
    // 判断项目
    templateContentDTOList.value[index].contentItemDTOList.push({
      meterReadingMode: 1,
      meterReadingModeDesc: "自动",
      meterReadingItem: "",
      unit: "",
      maxValue: "",
      minValue: "",
      eqpId: "",
      autoMeterReadingPoint: ""
    });
  }
};
// 删除抄表项目、判断项目某一行
const deleteMeterJudgeItem = async (index, row, $index) => {
  if (row.id) {
    templateContentDTOList.value[index].contentItemDTOList.splice($index, 1);
  } else {
    templateContentDTOList.value[index].contentItemDTOList.splice($index, 1);
  }
};
// 改变设备编号
const changeEqpId = equipDetail => {
  const { index, $index } = cellInfo.value;
  const { eqpId, eqpName } = equipDetail;
  templateContentDTOList.value[index].contentItemDTOList[$index].eqpId = eqpId || [];
  templateContentDTOList.value[index].contentItemDTOList[$index].eqpName = eqpName || "";
};
// 清空设备
const clearEquip = () => {
  // 1、遍历判断是否存在已选择的设备
  const item = templateContentDTOList.value?.find(checkRuleContent => {
    if (checkRuleContent.inspectItemType === 1) {
      const checkRuleContentItem = checkRuleContent.contentItemDTOList?.find(contentItem => contentItem.eqpId);
      return !!checkRuleContentItem;
    }
  });
  const tempItem = templateContentDTOListTemp.value?.find(checkRuleContent => {
    if (checkRuleContent.inspectItemType === 1) {
      const checkRuleContentItem = checkRuleContent.contentItemDTOList?.find(contentItem => contentItem.eqpId);
      return !!checkRuleContentItem;
    }
  });
  // 2、如果存在，提示设备清空,清空下拉框数据
  if (item || tempItem) {
    PxMessage.error("基本信息发生变化，设备及抄表点已被清空，请重新添加！");
  }
  // 3、清空
  if (item) {
    templateContentDTOList.value = templateContentDTOList.value?.map(checkRuleContent => {
      if (checkRuleContent.inspectItemType === 1) {
        const contentItemDTOList = checkRuleContent.contentItemDTOList?.map(contentItem => ({ ...contentItem, eqpName: "", eqpId: "" }));
        return { ...checkRuleContent, contentItemDTOList };
      } else {
        return checkRuleContent;
      }
    });
  }
  if (tempItem) {
    templateContentDTOListTemp.value = templateContentDTOListTemp.value?.map(checkRuleContent => {
      if (checkRuleContent.inspectItemType === 1) {
        const contentItemDTOList = checkRuleContent.contentItemDTOList?.map(contentItem => ({ ...contentItem, eqpName: "", eqpId: "" }));
        return { ...checkRuleContent, contentItemDTOList };
      } else {
        return checkRuleContent;
      }
    });
  }
};
defineExpose({
  form: checkRuleContentFormRef,
  clearEquip
});
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");

.inspect-table-view {
  .px-form-item {
    margin-bottom: 0;
  }
}
.equip-table.inspect-table-edit {
  :deep(td.px-table__cell) {
    padding: 0;
    height: auto !important;
    line-height: 1.2 !important;
    .cell {
      height: auto !important;
      line-height: 1.2 !important;
    }
  }
}
.popover-out {
  padding: 0;
}

.popover-list {
  padding: 8px 0;
  font-size: 16px;
  text-align: center;

  .popover-list-item {
    padding: 3px 0;
    cursor: pointer;

    &:hover {
      background: #ecf5ff;
    }
  }
}

.inspect-table-edit {
  .px-form-item {
    padding-top: 16px;
  }

  .flex-row {
    display: flex;
    align-items: center;
  }

  :deep(.px-table__cell) {
    padding: 0;
    height: 36px;
    line-height: 36px;
    .cell {
      height: 36px;
      line-height: 36px;
    }
  }

  .px-form-item__content {
    padding-top: 16px;
  }

  :deep(.px-table__header) {
    .must::before {
      margin-right: 4px;
      color: var(--px-color-danger);
      content: "*";
    }
  }
}
</style>
